<template>
  <div class="container_detail good-edit">
    <div class="header">
      <p>商品管理>添加/编辑{{returnName(type)}}</p>
      <el-button class="link" type="primary">
        <router-link :to="{path:'goodList',query: { pageIndex: currentPage }}" style="color: #fff;">返回</router-link>
      </el-button>
    </div>
    <div class="main">
      <el-form
        :model="user"
        :rules="rules"
        ref="user"
        label-width="150px"
        class=""
       >
       <el-form-item
          label="商品名称："
          prop="goodsName"
        >
           <el-input
              v-model="user.goodsName"
              placeholder="请输入"
            ></el-input>
        </el-form-item>
        <el-form-item
          label="价格："
          prop="price"
          v-if="user.type != 'real'"
        >
           <el-input
              v-if="user.type !='third' "
              v-model="user.price"
              placeholder="请输入"
            ></el-input>
             <span v-if="user.type == 'third'">{{user.price}}</span>
        </el-form-item>
        <el-form-item
          label="规格及价格："
          prop="price"
          v-if="user.type == 'real'"
        >   
            <div style="margin-bottom:10px" v-for="(item,index) in stockTable" :key="index" class="box">
               <el-input
                v-model="item.name"
                placeholder="请输入"
              ></el-input>
              <span style="margin:0 10px"></span>
              <el-input
                v-model="item.price"
                placeholder="请输入"
              ></el-input><span style="margin:0 10px;">元</span>
              <span @click="deleteTable(index)" style="margin:0 10px;cursor:pointer;color:red">删除</span>
            </div>
            <div @click="addBtn" style="cursor:pointer;color:#409EFF">添加</div>
             <span v-if="user.type == 'third'">{{user.price}}</span>
        </el-form-item>
        <el-form-item
          label="有效期："
          prop="validTime"
          v-if="user.type =='virtual' "
        >
             <el-date-picker
                v-model="user.validTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item
          label="有效期："
          prop="validTime"
          v-if="user.type =='third' "
        >
             <el-date-picker
                v-if="user.type !='third' "
                v-model="user.validTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                placeholder="选择日期">
            </el-date-picker>
            <span v-if="user.type == 'third'">{{user.validTime?user.validTime.split(' ')[0]:''}}</span>
        </el-form-item>
        <el-form-item
          label="库存数量："
          prop="stockNum"
        >
           <el-input  v-if="user.type !='third' "
              v-model="user.stockNum"
              placeholder="库存数量不可以小于已售出数量"
            ></el-input>
            <span v-if="user.type == 'third'">{{user.stockNum}}</span>
            <span v-if="id">已售出：{{user.saleNum}}</span>
        </el-form-item>
        <el-form-item
        label="商品类别："
        prop="title"
        >
           {{returnName(type)}}
        </el-form-item>
         <el-form-item
        label="商品分类："
        prop="categoryId"
        >
            <el-select v-model='user.categoryId' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option
                v-for="item in sortArr"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
         <el-form-item
        label="所属品牌："
        prop="brandId"
        >
            <el-select v-model='user.brandId' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option
                v-for="item in brandArr"
                :key="item.id"
                :label="item.brandName"
                :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
         <el-form-item
        label="所属城市："
        prop="city"
        >
            <el-select @change="provinceChange" v-model='user.province' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option label="全国" value="全省" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
                <el-option v-for="(item,index) in provinceArr" :key="index" :label="item.ssqname" :value="item.ssqid" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
            </el-select>
             <el-select  v-if="user.province!='全省'" @change="cityChange" v-model='user.city' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <!-- <el-option label="全部" value="" style="height: 30px;  line-height: 30px;width:200px;"></el-option> -->
                <el-option v-for="(item,index) in cityArr" :key="index" :label="item.ssqname" :value="item.ssqid" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
            </el-select>
        </el-form-item>
         <el-form-item
        label="购买须知："
        prop="notice"
        >
            <el-input
              v-model="user.notice"
              placeholder="请输入"
            ></el-input>
        </el-form-item>
        <el-form-item
          label="封面轮播图片："
          prop="photoIds"
        >
         <el-upload
            list-type="picture-card"
            class="normal-uploader"
            action=''
            :limit='9'
            multiple
            :file-list='fileList'
            :on-remove="handleImageRemove"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-plus"></i>
             <div class="el-upload__tip" slot="tip">上传图片比例建议为 200:200</div>
          </el-upload>
        </el-form-item>
        <el-form-item
            label="是否公开："
            prop="isOpen"
        >
            <el-select v-model='user.isOpen' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option label="是" value="y" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
                <el-option label="否" value="n" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
            </el-select>
        </el-form-item>
         <el-form-item
        label="是否上架："
        prop="isOn"
        >
            <el-select v-model='user.isOn' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option label="是" value="y" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
                <el-option label="否" value="n" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item
          label="运费："
          prop="freight"
          v-if="user.type == 'real'"
        >
           <el-input
              style="width:180px"
              v-model="user.freight"
              placeholder="请输入"
            ></el-input>
             <span>元</span>
        </el-form-item>
         <el-form-item
          label="包邮条件："
          prop="pinkageTerm"
          v-if="user.type == 'real'"
        >
           买满  <el-input
              style="width:150px"
              v-model="user.pinkageTerm"
              placeholder="请输入"
            ></el-input>
             <span>件</span>
        </el-form-item>
         <el-form-item
          label="不可配送区/县："
          prop="pinkageTerm"
          v-if="user.type == 'real'&&user.province!='全省'"
        >
           <div>
              <el-radio-group v-model="user.isDistributionArea">
                <el-radio   label="n">无</el-radio>
                <el-radio   label="y">有</el-radio>
              </el-radio-group>
           </div>
           <div class="box" v-if="user.isDistributionArea == 'y'">
             <div v-for="(item,index) in selectArea" :key="index">
              <el-select v-model='item.value' placeholder='-请选择-'  style="margin-right:10px;height: 30px;  line-height: 30px;width:100px;">
                  <el-option v-for="(list,num) in areaArr" :key="num" :label="list.ssqname" :value="list.ssqid" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
              </el-select>
              <div @click="deleteArea(index)" style="cursor:pointer;margin-left:30px;color: red;">删除</div>
             </div>
            <div @click="addArea" style="cursor:pointer;margin-left:10px;color: rgb(64, 158, 255);" class="add">添加</div>
           </div>
        </el-form-item>
        <el-form-item
          label="配送时间选择方式："
          prop="deliveryTime"
          v-if="user.type == 'real'"
        >
            <el-radio v-model="user.deliveryTime" label="配送时间">选择配送时间</el-radio>
            <el-radio v-model="user.deliveryTime" label="配送日">选择配送日</el-radio>
        </el-form-item>
         <el-form-item
          label="商品详情："
          prop="details"
        >
          <bg-editor
              :minHeight="300"
              :uploadUrl="upLoadUrl"
              :content="user.details"
              @editorData='editorInfo'
          >
          </bg-editor>
        </el-form-item>
        <el-form-item
          v-if="type != 'real'"
          label="适用门店信息："
          prop="applyShopMsg"
        >
          <bg-editor
              id="applyShopMsg"
              :minHeight="300"
              :uploadUrl="upLoadUrl"
              :content="user.applyShopMsg"
              @editorData='editorInfo1'
          >
          </bg-editor>
        </el-form-item>
        <el-form-item v-show="type == 'third'" class="coupon-table">
          <el-table  :data="thirdCouponDetailDTOs" :border='true'>
            <el-table-column  prop="sort" label="顺序"></el-table-column>
            <el-table-column  prop="url" label="链接"></el-table-column>
            <el-table-column  prop="couponPsw" label="兑换码"></el-table-column>
            <el-table-column  prop="validTime" label="有效期">
              <template slot-scope="scope">
                {{scope.row.validTime?scope.row.validTime.split(' ')[0]:scope.row.validTime}}
              </template>
            </el-table-column>
            <el-table-column  prop="price" label="价格"></el-table-column>
            <el-table-column  prop="sort" label="是否已售">
              <template slot-scope="scope">
                {{scope.row.isSale == 'y'?'是':'否'}}
              </template>
            </el-table-column>
            <el-table-column  prop="sort" label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status !='d'" @click="deleteRow(scope.row.sort)" type="primary" size="mini">删除</el-button>
                <span v-if="scope.row.status =='d'">已删除</span>
              </template>
            </el-table-column>
          </el-table>
           <el-button
           style="float:right;margin:10px"
            type="primary"
            size="mini"
            @click="addImport"
            >选择文件</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading1"
              @click="handleSave('user')"
              style="margin-left:150px"
            >保存</el-button>
          <el-button class="link" type="primary">
            <router-link :to="{path:'goodList',query: { pageIndex: currentPage }}" style="color: #fff;">返回</router-link>
        </el-button>
        </el-form-item>
      </el-form>
    </div>
      <el-dialog
        title="批量导入电子券"
        :visible.sync="dialogVisible1"
        width="40%"
       >
        <el-upload
          class="upload-demo"
          style="margin:0 auto;width:400px;"
          drag
          :file-list="fileList1"
          :action="importUrl1"
          :on-success="handUploadSuccess"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>
  </div>
</template>

<script>
let CONSTANT = require("../../constant/constant.js");
let common = require("../../common.js");
let countryArr = require("../../../static/city.json");
export default {
  data() {
    return {
      id: "",
      info: "",
      // 返回 导航页码
      currentPage: 1,
      dialogVisible: false,
      pictureUrl: "",
      typeArr:[
        {
            name:'实体商品',
            value:'real'
        },
         {
            name:'自营电子券',
            value:'virtual'
        },
        {
            name:'第三方电子券',
            value:'third'
        }
      ],
      user: {
        "brandId": "",
        "categoryId": "",
        "city": "",
        "details": "",
        "goodsName": "",
        "id": "",
        "isOn": "",
        "isOpen": "",
        "notice": "",
        "photoIds": "",
        "price": "",
        "province": "",
        "stockNum": "",
        "type": "",
        "validTime": "",
        pinkageTerm:'',
        freight:"",
        isDistributionArea:'',
        deliveryTime:'',

      },
      thirdCouponDetailDTOs:[],
      rules: {
        goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" }
        ],
        stockNum: [
          { required: true, message: "请输入库存数量", trigger: "blur" }
        ]
      },
      dialogVisible1:false,
      imageUrl:'',
      upLoadUrl:'',
      content:"",
      type:'',
      fileList:[],
      brandArr:[],
      sortArr:[],
      provinceArr :[],
      cityArr:[],
      fileList1:[],
      importUrl1:'',
      loading1:false,
      tableData:[],
      areaArr:[],
      stockTable:[
        {
          name:'',
          price:''
        }
      ],
      selectArea:[]
    };
  },
  watch:{
    'user.isDistributionArea':function(val){
      if(val == 'n'){
        this.selectArea = []
      }
    }
  },
  mounted() {
    this.provinceArr = countryArr.provinces.province
    this.id = this.$router.currentRoute.query.id;
    this.type = this.$router.currentRoute.query.type;
    this.user.type = this.type
    this.currentPage = this.$router.currentRoute.query.pageIndex
      ? this.$router.currentRoute.query.pageIndex
      : 1;
      let sessionId = sessionStorage.getItem("sessionId");
      this.upLoadUrl =
      CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS + "?sessionId=" + sessionId;
      this.importUrl1 = `${CONSTANT.URL.LIST.importEsThirdCouponDetailOnFile}?sessionId=${
        sessionId
      }`;
    this.getBrandList()
    this.getSort()
    if(this.id){
      this.getDetail();
    }
  },
  components: {
    "bg-editor": () => import("../common/bg-editor.vue")
  },
  methods: {
    addArea(){
      this.selectArea.push({
        value:''
      })
    },
    deleteArea(num){
      this.selectArea.splice(num,1)
    },
    deleteTable(index){
      this.stockTable.splice(index,1)
    },
    addBtn(){
      this.stockTable.push(
        {
          name:'',
          price:''
        }
      )
    },
    deleteRow(sort){
      let arr = this.thirdCouponDetailDTOs
      let num = 0
      arr.map((item,index)=>{
        if(item.sort == sort){
          arr[index].status = 'd'
        }
        if(item.status == 'a'){
          num++
        }
      })
       this.user.stockNum = num
    },
    handUploadSuccess(res) {
      if (res.status == -1) {
        this.$alert( res.error||"导入失败!", '', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      } else {
        let data = res.data.bussData.esGoodsDTO.esThirdCouponDetails
        console.log(data,'data')
        data = this.thirdCouponDetailDTOs.concat(data)
        data.forEach((item,index)=>{
          item.sort = index+1
          item.status = 'a'
        })
        if(data.length){
          this.user.stockNum = data.length
          this.user.price = data[0].price
          this.user.validTime = data[0].validTime
        }
        this.thirdCouponDetailDTOs = data
      }
      this.dialogVisible1 = false
    },
    addImport(){
      this.dialogVisible1 = true
    },
    provinceChange(){
        this.cityArr = []
        this.user.city = ''
        this.provinceArr.map(item=>{
            if(this.user.province == item.ssqid){
                this.cityArr = item.cities.city
            }
        })
    },
    cityChange(){
        this.areaArr = []
        this.cityArr.map(item=>{
            if(this.user.city == item.ssqid){
                this.areaArr = item.areas.area
            }
        })
        console.log(this.areaArr,'areaArr')
    },
    returnName(val){
        let str;
        this.typeArr.map(item=>{
            if(item.value == val){
                str = item.name
            }
        })
        return str
    },
    editorInfo(e) {
       this.user.details = e
    },
    editorInfo1(e) {
       this.user.applyShopMsg = e
    },
    getSort: function() {
      let url = CONSTANT.URL.LIST.findEsCategoryByPage;
      let data = {
          pageIndex: 1,
          pageSize:1000
      };
      this.loading = true;
      common.requestAjax(url, JSON.stringify(data), null, res => {
          let data = res.data;
          this.sortArr = data.bussData;
      });
    },
    handleImageRemove(file, fileList) {
      let list = []
      fileList.map((item, index) => {
        this.fileList.map((item1, index1) => {
          if (item.url == item1.url) {
            list.push(item1)
          }
        })
      })
      this.fileList = list
    },
    beforeAvatarUpload(file) {
      let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
      let param = {
        suffix: file.name.split(".")[1], // 文件后缀  png
        contentType: file.type // 文件类型  image/png
      };
      common.requestAjax(url,null, param, res => {
        this.upLoadUrl = res.data.bussData.uploadUrl;
        common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
          this.fileList.push({
            url: res.data.bussData.downloadUrl,
            fileKey: res.data.bussData.fileKey,
          })
          console.log(this.fileList,'fileListfileList')
        })
      });
    },
    setPassword(){
        this.user.psw = 123456
        this.user.psw2 = 123456
    },
    getBrandList: function() {
      let url = CONSTANT.URL.LIST.findEsBrandByPage;
      let data = {
        pageIndex:1,
        pageSize: 1000
      };
      common.requestAjax(url, JSON.stringify(data), null, res => {
        let data = res.data;
        this.brandArr = data.bussData;
      });
    },
    getDetail() {
      let url = CONSTANT.URL.LIST.findEsGoodsById;
      let data = { id: this.id }
      common.requestAjax(url, JSON.stringify(data), null, res => {
        let data = res.data.bussData;
        this.type = data.type
        this.user = {
            "brandId": data.brandDTO.id,
            "categoryId":data.categoryDTO.id,
            "city": data.city,
            "details":data.details,
            "goodsName":data.goodsName,
            "id": data.id,
            "isOn": data.isOn,
            "isOpen": data.isOpen,
            "notice": data.notice,
            "photoIds": '',
            "price": data.price,
            "province":  data.province,
            "stockNum":  data.stockNum,
            "type":  data.type,
            "validTime": data.validTime,
            saleNum:data.saleNum,
            freight:data.freight||'',
            pinkageTerm:data.pinkageTerm||'',
            isDistributionArea:data.isDistributionArea||'',
            deliveryTime:data.deliveryTime||''
        }
        setTimeout(()=>{
            $(`#summernote`).summernote('code',data.details)
        },1000)
          if(data.esThirdCouponDetails&&data.esThirdCouponDetails.length){
            data.esThirdCouponDetails.forEach((item,index)=>{
              item.sort = index+1
              item.status = 'a'
            })
            this.thirdCouponDetailDTOs = data.esThirdCouponDetails
         }
       
        this.provinceArr.map(item=>{
            if(this.user.province == item.ssqid){
                this.cityArr = item.cities.city
            }
        })
        this.cityArr.map(item=>{
            if(this.user.city == item.ssqid){
                this.areaArr = item.areas.area
            }
        })
        this.fileList = []
        data.photos.map(item=>{
            this.fileList.push({
              url:item.fileUrl,
              fileKey: item.fileKey,
            })
        })
        if(this.type == 'real'){
          let arr = data.modelPrice?data.modelPrice.split('::'):[]
          let arr1 = data.nonDistributionArea?data.nonDistributionArea.split(','):[]
          this.stockTable = []
          arr.map(item=>{
            let arr1 = item.split('&&')
            this.stockTable.push({
              name:arr1[0],
              price:arr1[1]
            })

          })
          this.selectArea = []
          arr1.map(item=>{
            this.selectArea.push({
              value:item
            })

          })
          this.user.freight = data.freight||''
          this.user.pinkageTerm = data.pinkageTerm||''
          this.user.isDistributionArea = data.isDistributionArea||''
          this.user.deliveryTime = data.deliveryTime||''
          console.log(this.user,'this.stockTable')
        }else{
          this.user.applyShopMsg = data.applyShopMsg
          setTimeout(()=>{
            $(`#applyShopMsg`).summernote('code',data.applyShopMsg)
        },1000)
        }
      });
    },
    checkImage(url) {
      this.pictureUrl = url;
      this.dialogVisible = true;
    },
    handleSave: function(formName) {
        let arr = []
        if(this.fileList.length){
            this.fileList.map(item=>{
                arr.push(item.fileKey)
            })
            this.user.photoIds = arr.join(',')
        }
      if(this.type == 'third'){
        this.user.thirdCouponDetailDTOs = this.thirdCouponDetailDTOs
      }
      if(this.type == 'real'){
        this.user.price = '0'
        let arr = [],arr1=[]
        this.stockTable.map(item=>{
          arr.push(item.name+'&&'+item.price)
        })
        this.user.modelPrice = arr.join('::')
        if(this.selectArea.length){
          this.selectArea.map(item=>{
            arr1.push(item.value)
          })
          this.user.nonDistributionArea = arr1.join(',')
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let thirdArr = this.thirdCouponDetailDTOs
          if(thirdArr.length){
            let price
            thirdArr.map(item=>{
              if(item.status == 'a'){
                price = item.price
                return
              }
            })
            this.user.price = price
          }
           console.log(this.user,'this.user.thirdCouponDetailDTOs')
          this.loading1 = true
          if(this.type != 'real'){
              this.user.validTime =  this.user.validTime?this.user.validTime.split(' ')[0]+' '+'23:59:59':''
          }
          let url = CONSTANT.URL.LIST.saveEsGoods;
          common.requestAjax(url, JSON.stringify(this.user), null, res => {
            this.loading1 = false
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.$router.push({
                path: "/goodList",
                query: { pageIndex: this.currentPage }
              });
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss">
.coupon-table{
  .el-form-item__content{
    margin-left: 0!important;
  }
}
.good-edit {
  .el-form-item {

    
  }
    .el-input {
      width:220px;
    }
    .el-select {
      width: 220px;
      .el-input {
        width: 100%;
      }
    }

  .item-value {
    .el-input {
      width:220px;
    }
    .el-select {
      width: 220px;
      .el-input {
        width: 100%;
      }
    }
  }
}
</style>

